<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/10/10
 * Time: 10:15
 */
namespace Home\Controller;
use Think\Controller;

class CountVisitIpController extends Controller{
    protected  $db_model = null;

    public function index(){
       $this->db_model =  D('CountVisit');

//        $data = array(
//            'ip'    => '15456456',
//            'time'  => time(),
//        );
//        $this->db_model->create($data);
////        $ok = $this->db_model->add();
////        dump($ok);
//        dump($this->db_model->select());


        $this->countVisit();

        $this->display('CountVisit/index');
    }


    /**
     * 创建 访客统计 模块
     */
    public function install(){
        //获取表前缀
        $pre = C('DB_PREFIX');
        $sql = "create table if not exists ".$pre."count_visit(
id int not null auto_increment,
`ip` bigint not null comment '来访者ip',
`url` varchar(255) not null comment '访问的url地址',
`vtime` int comment '访问时间',
PRIMARY key (id)
)engine=myisam default charset=utf8 comment='访客统计数据库';";
        $db = D('');

        $create_table = $db->execute($sql);
        if(!$create_table){
            echo $db->getError();
        }else{
            //表 创建成功!
        }
    }


    /**
     * 访问统计 入口
     */
    public function countVisit(){
        //获取 当前用户的ip 值。
        $data['ip'] = ip2long($_SERVER['REMOTE_ADDR']);
        //当前访问时间
        $data['vtime'] = time();
        //当前访问url
        $data['url'] = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
//        dump($_SERVER);
//        dump($data);exit;
        //判断有没有 session
        if(session('COUNT_VISIT_KEY') == 'COUNT_VISIT'){
            //有了 不做任何 操作
        }else{
            //没有 记录 session  记录 count_visit
            session('COUNT_VISIT_KEY','COUNT_VISIT');
            //保存 数据
            $ok = D('CountVisit')->add($data);
        }
    }


    /**
     * 打印 统计数据
     */
    public function print_count(){
        $name = '客户访问统计';
        $model = D('CountVisit');

        $start = 0;
        $end = time();
        $map['vtime'] = array('BETWEEN',array($start,$end));
        A('Home/PHPExcel')->excel_out($name, $model,$map);
    }
}